package com.fingard.dsp.bank.directbank.wjrb01;

import com.fingard.dsp.bank.directbank.PaymentState;
import com.fingard.dsp.bank.directbank.bankInterface.ISinglePay;
import com.fingard.dsp.bank.reqrespobj.single.*;
import com.fingard.dsp.bank.reqrespobj.single.detail.RetAtsSglDetail;
import com.fingard.net.ConnState;
import com.fingard.xml.XElement;
import com.fingard.xml.XmlTextReader;
import com.fingard.xml.XmlTextWriter;
/**
 * @author: liuxb
 * @create: 2019-12-17 15:19
 * @version: 1.0
 **/
public class WJRB01SinglePay extends WJRB01Base implements ISinglePay {
    @Override
    public RetAtsSingle d_1908_SglPay(ReqSingle p_req1908) throws Exception {
        // 返回给ATS的对象
        RetAtsSingle retAtsSingle = new RetAtsSingle(p_req1908.reqHeader);
        RetAtsSglDetail detail = new RetAtsSglDetail();//用于提取银行返回报文信息的对象
        try {
            //赋值通用参数
            WJRB01Header header = new WJRB01Header();
            WJRB01Base base = new WJRB01Base();
            if ("1".equals(p_req1908.singleDetail.sameBnk)) {//同行
                header.TrsCode = "B2EBankInnerTransfer";
            } else if ("0".equals(p_req1908.singleDetail.sameBnk)) {//他行
                header.TrsCode = "B2ECrossBankTransfer";
            }
            header.ERPJnlNo = base.getQryTransID();// ERP（财务系统）交易流水号
            header.ERPTrsTimestamp = p_req1908.reqHeader.transTime;//指令请求时间
            //拼接请求报文头
            XmlTextWriter xmlTextWriter = new XmlTextWriter();
            writeCommonHeader(xmlTextWriter, header);
            //拼接请求报文体
            xmlTextWriter.writeStartElement("Body");
            xmlTextWriter.writeStartElement("List");
            XElement tmpXElement = new XElement("Map", "");
            tmpXElement.addChild(new XElement("PayerAcNo", p_req1908.singleDetail.payAct));//转出账号
            tmpXElement.addChild(new XElement("PayeeAcName", p_req1908.singleDetail.recName));//转入户名
            tmpXElement.addChild(new XElement("PayeeAcNo", p_req1908.singleDetail.recAct));//转入账号
            tmpXElement.addChild(new XElement("Amount", p_req1908.singleDetail.payAmount));//金额
            tmpXElement.addChild(new XElement("Remark", p_req1908.singleDetail.purpose));//用途

            if ("0".equals(p_req1908.singleDetail.sameBnk)) {//他行
                tmpXElement.addChild(new XElement("Currency", convertCurToBank(p_req1908.singleDetail.payCur)));//付方币种
                tmpXElement.addChild(new XElement("UnionDeptId", p_req1908.singleDetail.cnapsCode));//转入行清算行号

                String priority = "0";//转账方式 1：一般汇款(大额) 0：小额快汇
                String paySpd = "1002";//1001：加急，1002：普通

                String urgentFlag = getBankConfig().getValueAsString("UrgentLargeAmount");
                if (Double.parseDouble(p_req1908.singleDetail.payAmount) > 50000) {
                    priority = "1";
                    paySpd = "1001";
                }
                tmpXElement.addChild(new XElement("PayPathCode", paySpd));
                tmpXElement.addChild(new XElement("Priority", priority));
            }
            nodeAnalysis(p_req1908.singleDetail.srcXElement, tmpXElement, getCharset());//分析报文节点
            xmlTextWriter.writeXElement(tmpXElement);
            xmlTextWriter.writeEndDocument();


            // 发送报文到银行
            String[] bankResult = sendToBank(xmlTextWriter.toXmlString(), header);

            //模拟银行返回
//            String s = "<Message>\n" +
//                    "\t<Head>\n" +
//                    "\t\t\t<IBSReturnCode>000000</IBSReturnCode>\n" +
//                    "\t\t\t<IBSReturnMsg>银企交易成功！</IBSReturnMsg>\n" +
//                    "<IBSJnlNo>12121</IBSJnlNo>\n" +
//                    "\t</Head>\n" +
//                    "\t<Body>\n" +
//                    "\t\t<List>\n" +
//                    "\t\t\t<Map>\n" +
//                    "\t\t\t\t<ReturnCode>000000</ReturnCode>\n" +
//                    "\t\t\t\t<ReturnMsg>成功！</ReturnMsg>\n" +
//                    "<ErrorCode>2</ErrorCode>\n" +
//                    "<PayerAcNo>343434</PayerAcNo>\n" +
//                    "<Amount>1220.88</Amount>\n" +
//                    "\t\t\t</Map>\n" +
//                    "\t\t</List>\n" +
//                    "</Body>\n" +
//                    "</Message>\n";
//            String[] bankResult = new String[]{"", s};

            if (bankResult[0].length() == 0) {
                StringBuilder tmpSbMsg = new StringBuilder();// 接收提示信息
                XmlTextReader tmpBkReader = loadBankRespXmlReader(bankResult[1], tmpSbMsg);
                if (tmpBkReader != null) {// 返回内容不为空
                    String IBSReturnCode = tmpBkReader.getFirstText("/Message/Head/IBSReturnCode");
                    String IBSJnlNo = tmpBkReader.getFirstText("/Message/Head/IBSReturnMsg");
                    detail.reqSeqID = tmpBkReader.getFirstText("/Message/Head/IBSJnlNo");// 交易流水号
                    if ("000000".equals(IBSReturnCode)) {
                        String returnCode = tmpBkReader.getFirstText("/Message/Body/List/Map/ReturnCode");
                        String returnMsg = tmpBkReader.getFirstText("/Message/Body/List/Map/ReturnMsg");
                        String ErrorCode = tmpBkReader.getFirstText("/Message/Body/List/Map/ErrorCode");
                        detail.transAmt = tmpBkReader.getFirstText("/Message/Body/List/Map/Amount");//金额
//                        String FeeAmount = tmpBkReader.getFirstText("/Message/Body/List/Map/FeeAmount");//手续费
//                        String PayerAcNo = tmpBkReader.getFirstText("/Message/Body/List/Map/PayerAcNo");//转出账号
//                        String PayeeAcNo = tmpBkReader.getFirstText("/Message/Body/List/Map/PayeeAcNo");//转入账号
//                        String PayeeAcName = tmpBkReader.getFirstText("/Message/Body/List/Map/PayeeAcName");//转入户名
                        detail.respCode = "0";
                        detail.respInfo = returnMsg;
//                        if("000000".equals(returnCode)){
//                            detail.transState=returnCode;
//                        }else {
//                            detail.transState=ErrorCode;
//                        }
                        detail.reqSeqID = p_req1908.singleDetail.askNumber;// 交易流水号
                        detail.transState = returnCode;
                        detail.payInfoCode = returnCode;
//                        detail.transAmt = tmpBkReader.getFirstText("/Message/Body/List/Map/PayerBalance");//转出帐号余额
                    } else {
                        detail.respCode = "-1";
                        detail.respInfo = IBSJnlNo;
                    }
                } else {
                    detail.respCode = "-1";
                    detail.respInfo = tmpSbMsg.toString();
                }
            } else if (bankResult[0].equals(ConnState.FAIL)) {
                detail.respCode = "0";
                detail.respInfo = bankResult[1];
                detail.reqSeqID = p_req1908.singleDetail.askNumber;
                detail.transState = PaymentState.FAIL_Payment;
                detail.payInfoCode = bankResult[0];
            } else {
                detail.respCode = "-1";
                detail.respInfo = bankResult[1];
                detail.reqSeqID = p_req1908.singleDetail.askNumber;
            }


        } catch (Exception ex) {
            detail.respCode = "-1";
            detail.respInfo = ex.getMessage();
            ex.printStackTrace();
        }
        retAtsSingle.writeRetDetail(detail);
        retAtsSingle.writeEnd();
        return retAtsSingle;
    }

    @Override
    public RetAtsSingle d_1944_QrySglPay(ReqQrySingle p_req1944) throws Exception {
        RetAtsSingle retAtsSingle = new RetAtsSingle(p_req1944.reqHeader);
        RetAtsSglDetail detail = new RetAtsSglDetail();
        try {
            XmlTextWriter xmlTextWriter = new XmlTextWriter();
            WJRB01Header header = new WJRB01Header();
            header.TrsCode = "B2ETrsResultQry";
            header.ERPJnlNo = p_req1944.reqHeader.transSeqID;
            header.ERPTrsTimestamp = p_req1944.reqHeader.transTime;//指令请求时间

            //拼接请求报文头
            writeCommonHeader2(xmlTextWriter, header);
            //拼接请求报文体
            xmlTextWriter.writeStartElement("Body");
            xmlTextWriter.writeElementString("HistoryERPJnlNo", p_req1944.askNumber);//原erp交易流水号
            xmlTextWriter.writeEndDocument();

            // 发送报文到银行
            String[] bankResult = sendToBank(xmlTextWriter.toXmlString(), header);

            //模拟银行返回
//            String s = "<Message>\n" +
//                    "\t<Head>\n" +
//                    "\t\t\t<IBSReturnCode>000000</IBSReturnCode>\n" +
//                    "\t\t\t<IBSReturnMsg>银企交易成功！</IBSReturnMsg>\n" +
//                    "\t</Head>\n" +
//                    "<Body>\n" +
//                    "\t\t\t\t<ReturnCode>000000</ReturnCode>\n" +
//                    "\t\t\t\t<TrsStateMsg>成功！</TrsStateMsg>\n" +
//                    "\t\t\t\t<TrsStateCode>03</TrsStateCode>\n" +
//                    "\t</Body>\n" +
//                    "</Message>\n";
//            String[] bankResult = new String[]{"", s};

            if (bankResult[0].length() == 0) {
                StringBuilder tmpSbMsg = new StringBuilder();
                XmlTextReader xmlSbReader = loadBankRespXmlReader(bankResult[1], tmpSbMsg);
                if (xmlSbReader != null) {
                    String respCode = xmlSbReader.getFirstText("/Message/Head/IBSReturnCode");
                    String respInfo = xmlSbReader.getFirstText("/Message/Head/IBSReturnMsg");
                    if ("000000".equals(respCode)) {//交易成功
                        detail.respCode = "0";
                        String str = xmlSbReader.getFirstText("/Message/Body/TrsStateCode");//被查询的交易之结果代码
                        detail.respInfo = xmlSbReader.getFirstText("/Message/Body/TrsStateMsg");//交易状态信息
                        detail.reqSeqID = p_req1944.askNumber;
                        detail.transState = str;
                        detail.payInfoCode = str;
//                        detail.payInfoCode = xmlSbReader.getFirstText("/Message/Body/List/Map/ReturnCode");//错误码
                    } else if (respCode != null && "999999".equals(respCode)) {// 如果是ct通讯机校验错误，或者通讯失败
                        retAtsSingle.writeRespCode("-1");
                        retAtsSingle.writeRespInfo(respInfo);
                    } else {
                        detail.respCode = "-1";
                        detail.respInfo = respInfo;
                    }

                } else {
                    detail.respCode = "-1";
                    detail.respInfo = tmpSbMsg.toString();
                }

            } else {
                detail.respCode = "-1";
                detail.respInfo = bankResult[1];
            }


        } catch (Exception ex) {
            detail.respCode = "-1";
            detail.respInfo = ex.getMessage();
            ex.printStackTrace();
        }

        retAtsSingle.writeRetDetail(detail);
        return retAtsSingle;
    }

    @Override
    public RetAtsSingleBat d_1908BAT_SglBatPay(ReqSingleBat p_req1908BAT) throws Exception {
        return null;
    }

    @Override
    public RetAtsSingleBat d_1944BAT_QrySglBatPay(ReqQrySingleBat p_req1944BAT) throws Exception {
        return null;
    }
}
